<template>
  <div class="ddio-synchro">
    <div class="synchro-tit"><em /><span>{{ $t('ddio.timingSynchronize') }}</span></div>
    <div class="form">
      <el-form label-position="right" label-width="120px" :model="form">
        <el-form-item :label="$t('ddio.start')">
          <el-switch v-model="startTast" @change="changeTaskStatus" />
        </el-form-item>
        <el-form-item :label="$t('ddio.way')">
          <el-radio-group v-model="form.radioTime" @change="changeTastWay">
            <el-radio label="everyday">{{ $t('ddio.everyday') }}</el-radio>
            <el-radio label="week">{{ $t('ddio.week') }}</el-radio>
            <el-radio label="month">{{ $t('ddio.month') }}</el-radio>
            <el-radio label="lastday">{{ $t('ddio.lastday') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="form.radioTime === 'week'"
          :label="$t('ddio.week')"
        >
          <el-select
            v-model="form.weekday"
            class="select-box"
            :multiple="true"
            :placeholder="$t('ddio.selectWeek')"
          >
            <el-option
              v-for="item in weekOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-show="form.radioTime === 'month'"
          :label="$t('ddio.month')"
        >
          <el-select
            v-model="form.monthday"
            class="select-box"
            :multiple="true"
            :placeholder="$t('ddio.selectMonth')"
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('ddio.time')">
          <el-time-picker
            v-model="form.time"
            class="select-box"
            :placeholder="$t('ddio.selectTime')"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-haspermi="['bxy:ddio-setting:apply']" class="button" type="primary" @click="updateTast">{{
            $t('ddio.synchronize')
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider />
    <div class="synchro-tit"><em /><span>{{ $t('ddio.manualSynchronize') }}</span></div>
    <el-form label-position="right" label-width="120px">
      <el-form-item :label="$t('route.ddioOrg')">
        <span style="margin-left:10px;">{{ $t('ddio.thirdParty') }}：</span>
        <el-select
          v-model="thirdPartyId"
          :placeholder="$t('common.pleaseSelect')"
          style="width:150px;margin-right:10px;"
        >
          <el-option
            v-for="item in thirdpartiesList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-button
          v-haspermi="['bxy:ddio-setting:orgSyncData']"
          class="button"
          type="primary"
          @click="controlSynchroDialog(true,'org')"
        >
          {{ $t('ddio.syncData') }}
        </el-button>
      </el-form-item>
      <el-form-item :label="$t('route.ddio')">
        <el-button
          v-haspermi="['bxy:ddio-setting:UserSyncData']"
          class="button"
          type="primary"
          @click="controlSynchroDialog(true,'employee')"
        >
          {{ $t('ddio.syncData') }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog :title="$t('user.synchro')" :visible.sync="synchroVisible">
      <div class="synchro-form">
        <div class="synchro-item">
          <el-radio v-model="mode" label="0">{{
            $t('user.fullSync')
          }}</el-radio>
        </div>
        <div class="synchro-item">
          <el-radio v-model="mode" label="1">{{
            $t('user.incrementalSync')
          }}</el-radio>
        </div>
        <el-button
          v-if="synchroType==='org'"
          class="synchro-btn"
          type="warning"
          @click="reloadDepartment"
        >{{ $t('ddio.syncData') }}</el-button>
        <el-button
          v-if="synchroType==='employee'"
          class="synchro-btn"
          type="warning"
          @click="syncUser"
        >{{ $t('ddio.syncData') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTimingTasksConfigure,
  updateTimingTaskConfigure,
  startTimingTask,
  pauseTimingTask,
} from '@/api/console';
import * as settings from '@/api/settings';
import doodApi from '@/api/ddio';

export default {
  data() {
    return {
      form: {
        radioTime: 'everyday',
        weekday: [],
        monthday: [],
        time: '',
      },
      startTast: false,
      weekOptions: [],
      monthOptions: [],
      id: '', // 任务id
      mode: '0',
      synchroVisible: false,
      thirdPartyId: null,
      thirdpartiesList: [],
      synchroType: null,
    };
  },
  watch: {
    '$i18n.locale': {
      handler(val, oldVal) {
        this.newWeekDay();
      },
    },
  },
  created() {
    this.newMonthDay();
    this.newWeekDay();
    this.getTimeTaskSetting();
    this.getThirdpartiesList();
  },
  methods: {
    // 构造每周的数据,用于国际化切换可以动态改变,直接在data里赋值切换国际化不会改变
    newWeekDay() {
      this.weekOptions = [
        {
          label: this.$t('ddio.monday'),
          value: 'MON',
        },
        {
          label: this.$t('ddio.tuesday'),
          value: 'TUE',
        },
        {
          label: this.$t('ddio.wednesday'),
          value: 'WED',
        },
        {
          label: this.$t('ddio.thursday'),
          value: 'THU',
        },
        {
          label: this.$t('ddio.friday'),
          value: 'FRI',
        },
        {
          label: this.$t('ddio.saturday'),
          value: 'SAT',
        },
        {
          label: this.$t('ddio.sunday'),
          value: 'SUN',
        },
      ];
    },
    // 构造每个月的日期。这里日期只到28号，考虑到有的月份没有29，30，31，特此添加了一个每个月最后一天的选项
    newMonthDay() {
      for (let i = 1; i <= 28; i++) {
        this.monthOptions.push({
          label: i,
          value: i,
        });
      }
    },
    // 获取同步定时任务配置
    async getTimeTaskSetting() {
      // FIXME (ZK) 获取的定时任务id前端暂时写死 1
      const result = await getTimingTasksConfigure('1');
      // 解析接口返回的表达式
      this.exPressToDate(result.data.cronExpression);
      this.id = result.data.id;
      if (result.data.jobStatus !== 'START') {
        this.startTast = false;
        return;
      }
      this.startTast = true;
    },
    // 更新同步定时任务
    async updateTast() {
      if (this.form.radioTime === 'week' && !this.form.weekday.length) {
        this.$message({
          message: this.$t('ddio.needSelectWeek'),
          type: 'warning',
        });
        return;
      }
      if (this.form.radioTime === 'month' && !this.form.monthday.length) {
        this.$message({
          message: this.$t('ddio.needSelectMonth'),
          type: 'warning',
        });
        return;
      }
      const express = this.switchExpress(this.form.monthday, this.form.weekday);
      const result = await updateTimingTaskConfigure(
        {
          cronExpression: express,
        },
        this.id
      );
      if (result.status === 200) {
        this.$message({
          message: this.$t('ddio.syncSuccess'),
          type: 'success',
        });
        this.getTimeTaskSetting();
      }
    },
    // 切换开启同步
    changeTaskStatus() {
      if (this.startTast) {
        this.startSyncTast();
      } else {
        this.stopSyncTast();
      }
    },
    // 开启同步
    async startSyncTast() {
      const result = await startTimingTask(this.id);
      if (result.status === 200) {
        this.$message({
          message: this.$t('ddio.opened'),
          type: 'success',
        });
        this.getTimeTaskSetting();
      }
    },
    // 关闭同步
    async stopSyncTast() {
      const result = await pauseTimingTask(this.id);
      if (result.status === 200) {
        this.$message({
          message: this.$t('ddio.closed'),
          type: 'success',
        });
        this.getTimeTaskSetting();
      }
    },
    // 选择同步的方式
    changeTastWay() {
      console.log(this.form.radioTime);
      switch (this.form.radioTime) {
        case 'everyday':
          this.form.weekday = [];
          this.form.monthday = ['*'];
          break;
        case 'week':
          this.form.weekday = [];
          this.form.monthday = [];
          break;
        case 'month':
          this.form.weekday = [];
          this.form.monthday = [];
          break;
        case 'lastday':
          this.form.weekday = [];
          this.form.monthday = ['L'];
          break;
        default:
          break;
      }
    },
    // 将同步方式转为表达式
    switchExpress(month, week) {
      console.log(this.form.time);
      let time = this.form.time || '00:00:00';
      time = time.split(':');
      const monthday = month.length ? month.join(',') : '?';
      const weekday = week.length ? week.join(',') : '?';
      const second = Number(time[2]);
      const minute = Number(time[1]);
      const hour = Number(time[0]);
      return (
        second +
        ' ' +
        minute +
        ' ' +
        hour +
        ' ' +
        monthday +
        ' ' +
        '*' +
        ' ' +
        weekday
      );
    },
    // 将从接口获取的表达式解析回显到页面
    exPressToDate(value) {
      let date = value;
      date = date.split(' ');
      const second = date[0].length > 1 ? date[0] : `0${date[0]}`;
      const minute = date[1].length > 1 ? date[1] : `0${date[1]}`;
      const hour = date[2].length > 1 ? date[2] : `0${date[2]}`;
      this.form.time = hour + ':' + minute + ':' + second;
      this.form.monthday =
        date[3] !== '*' && date[3] !== '?' ? date[3].split(',') : [];
      this.form.weekday =
        date[5] !== '*' && date[5] !== '?' ? date[5].split(',') : [];
      if (this.form.weekday.length) {
        this.form.radioTime = 'week';
        this.form.monthday = [];
        return;
      }
      if (this.form.monthday[0] === 'L') {
        this.form.radioTime = 'lastday';
        return;
      }
      if (this.form.monthday.length) {
        this.form.radioTime = 'month';
        this.form.weekday = [];
        return;
      }
      if (!this.form.monthday.length && !this.form.weekday.length) {
        this.form.radioTime = 'everyday';
        this.form.weekday = [];
        this.form.monthday = ['*'];
        return;
      }
    },
    /**
     * 重新同步组织架构
     */
    async reloadDepartment() {
      const res = await doodApi.syncOrganization(Number(this.mode));
      if (res.data.code === '0') {
        await this.$message({
          message: this.$t('ddio.successReloadDepartment'),
          type: 'success',
        });
        this.controlSynchroDialog(false);
      } else {
        await this.$message({
          message: res.message,
          type: 'error',
        });
      }
    },
    /**
     * 显示/隐藏 同步模式弹窗
     * @param {Boolean} state  ture or false
     * @param {String} type org or employee
     */
    controlSynchroDialog(state, type) {
      this.synchroVisible = state;
      this.synchroType = type;
    },
    /**
     * 获取第三方列表
     */
    async getThirdpartiesList() {
      const res = await settings.getThirdpartiesList();
      this.thirdpartiesList = res.data;
      this.thirdPartyId = this.thirdpartiesList[0].id;
      this.treeReload = true;
    },
    /**
     * 同步人员信息
     */
    async syncUser() {
      const res = await doodApi.syncUser(Number(this.mode));
      if (res.data.code === '0') {
        await this.$message({
          message: this.$t('ddio.successReloadDoodUser'),
          type: 'success',
        });
        this.controlSynchroDialog(false);
      } else {
        await this.$message({
          message: res.message,
          type: 'error',
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.form {
  margin-top: 20px;
}
.select-box {
  width: 38%;
}
.button {
  width: 120px;
}
.ddio-synchro {
  padding-top: 20px;
  .synchro-tit {
    line-height: 44px;
    padding-left: 20px;
    em {
      display: inline-block;
      vertical-align: middle;
      width: 4px;
      height: 16px;
      background-color: #409eff;
    }
    span {
      display: inline-block;
      vertical-align: middle;
      margin-left: 5px;
    }
  }
}
.synchro-form {
  margin-top: -20px;
  overflow: hidden;
  .synchro-item {
    margin: 20px 0;
    padding-left: 40px;
    span {
      display: inline-block;
      vertical-align: top;
    }
  }
  .synchro-btn {
    float: right;
  }
}
</style>
